#!/usr/bin/env python
# _*_ coding:utf-8 _*_
#
# Copyright(c) http://m.ecpark.cn/
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.

# import pika
import logging

# import json

log = logging.getLogger(__name__)

formatter = logging.basicConfig(level=logging.DEBUG,
                                format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
                                datefmt='%a, %d %b %Y %H:%M:%S')

try:
    from .rabbitmq_info_config import db_plat_mysql_backup_startup_exchange
    from .rabbitmq_info_config import db_plat_mysql_backup_startup_queue
    from .rabbitmq_info_config import db_plat_mysql_backup_finished_exchange
    from .rabbitmq_info_config import db_plat_mysql_backup_finished_queue

    from mysql_backup_option import db_pt_request_url

except ImportError as e:
    from .rabbitmq_info_config import db_plat_mysql_backup_startup_exchange
    from .rabbitmq_info_config import db_plat_mysql_backup_startup_queue
    from .rabbitmq_info_config import db_plat_mysql_backup_finished_exchange
    from .rabbitmq_info_config import db_plat_mysql_backup_finished_queue

    from mysql_backup_option import db_pt_request_url

    log.exception(str(e))

try:
    from urllib.parse import urlencode
    from urllib.request import Request, urlopen

except ImportError as e:
    from urllib.parse import urlencode
    from urllib.request import Request, urlopen

    log.exception(str(e))


# def get_rabbitmq_connection(rabbitmq_host, rabbitmq_port, rabbitmq_user, rabbitmq_psw, virtual_host='/'):
#     credentials = pika.PlainCredentials(rabbitmq_user, rabbitmq_psw)
#     connection = pika.BlockingConnection(
#         pika.ConnectionParameters(rabbitmq_host, rabbitmq_port, virtual_host, credentials))
#     return connection


# def rabbitmq_message_publish(connection, exchange, queue, message, exchange_type='direct'):
#     channel = connection.channel()
#     channel.queue_declare(queue=queue)
#     channel.exchange_declare(exchange=exchange, exchange_type=exchange_type, durable=True)
#     channel.queue_bind(exchange=exchange, routing_key=queue,
#                        queue=queue)
#     if isinstance(message, dict):
#         channel.basic_publish(exchange=exchange,
#                               routing_key='',
#                               body=json.dumps(message))
#     else:
#         channel.basic_publish(exchange=exchange,
#                               routing_key='',
#                               body=message)
#     connection.close()

# def message_send1(queue, message):
#     request_url = db_pt_request_url
#     log.info(request_url)
#     url_init = GetURL(request_url, timeout=20)
#     message = {'queue': queue,
#                'body': str(message)}
#     body = url_init.request(method="POST", **message)
#     log.info(body)
#     return body

def message_send(queue, message):
    return
    request_url = db_pt_request_url
    log.info(request_url)
    message = {'queue': queue,
               'body': str(message)}

    request = Request(db_pt_request_url, urlencode(message).encode())
    body = urlopen(request).read().decode()
    log.info(body)
    return body


class MySQLBackupStartupInfoIntoRabbitMQ(object):
    def __init__(self):
        self.db_plat_mysql_backup_startup_exchange = db_plat_mysql_backup_startup_exchange
        self.db_plat_mysql_backup_startup_queue = db_plat_mysql_backup_startup_queue

        self.mysql_backup_startup_publish_info = {}

    def set_backup_startup_info(self, backup_startup_info):
        self.mysql_backup_startup_publish_info = backup_startup_info

    def set_pid_info(self, pid):
        self.mysql_backup_startup_publish_info.update({'pid': pid})

    def backup_startup_publish(self):
        body = message_send(self.db_plat_mysql_backup_startup_queue,
                            self.mysql_backup_startup_publish_info)
        return body


class MySQLBackupFinishedInfoIntoRabbitMQ(object):
    def __init__(self):
        self.db_plat_mysql_backup_finished_exchange = db_plat_mysql_backup_finished_exchange
        self.db_plat_mysql_backup_finished_queue = db_plat_mysql_backup_finished_queue
        self.mysql_backup_finished_publish_info = {}

    def set_backup_finished_info(self, backup_finished_info):
        self.mysql_backup_finished_publish_info = backup_finished_info

    def backup_startup_publish(self):
        # request_url = "http://127.0.0.1:7383/api_dbpt/rabbitmq/sender"
        # log.info(request_url)
        # url_init = GetURL(request_url, timeout=20)
        # message = {'queue': self.db_plat_mysql_backup_finished_queue,
        #            'body': str(self.mysql_backup_finished_publish_info)}
        # body = url_init.request(method="POST", **message)
        # log.info(body)
        body = message_send(self.db_plat_mysql_backup_finished_queue,
                            self.mysql_backup_finished_publish_info)
        return body
